<template>
  <div class="bill-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="未缴账单" name="UNPAID"></el-tab-pane>
      <el-tab-pane label="已缴账单" name="PAID"></el-tab-pane>
      <el-tab-pane label="逾期账单" name="OVERDUE"></el-tab-pane>
    </el-tabs>

    <el-table :data="billList" border>
      <el-table-column label="账单编号" prop="billNo" />
      <el-table-column label="费用类型" prop="typeName" />
      <el-table-column label="金额" prop="amount" :formatter="formatMoney" />
      <el-table-column label="到期日" prop="dueDate" />
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 'UNPAID'" type="warning">未缴</el-tag>
          <el-tag v-if="scope.row.status === 'PAID'" type="success">已缴</el-tag>
          <el-tag v-if="scope.row.status === 'OVERDUE'" type="danger">逾期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            v-if="scope.row.status !== 'PAID'"
            type="primary"
            size="mini"
            @click="handlePay(scope.row)"
          >
            立即支付
          </el-button>
          <el-button
            v-else
            type="text"
            size="mini"
            @click="viewReceipt(scope.row)"
          >
            查看收据
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getBillList } from "@/api/fee/bill";
import { payOrder } from "@/api/fee/payment";
import { wechatPay } from "@/utils/wxPay"; // 微信支付工具

export default {
  data() {
    return {
      activeTab: "UNPAID",
      billList: []
    };
  },
  watch: {
    activeTab() {
      this.loadBills();
    }
  },
  created() {
    this.loadBills();
  },
  methods: {
    loadBills() {
      getBillList({ status: this.activeTab }).then(response => {
        this.billList = response.rows;
      });
    },
    formatMoney(row, column, value) {
      return "¥" + value.toFixed(2);
    },
    handlePay(bill) {
      // 调用支付接口
      payOrder(bill.billId).then(response => {
        // 调起微信支付
        wechatPay(response.payParams, {
          success: () => {
            this.$message.success("支付成功");
            this.loadBills();
          },
          fail: (err) => {
            this.$message.error("支付失败：" + err.errMsg);
          }
        });
      });
    },
    viewReceipt(bill) {
      // 查看电子收据
      window.open(process.env.VUE_APP_BASE_API + "/file/receipt/" + bill.receiptNo);
    }
  }
};
</script>
